package fons.model.ontology.calculation;

import java.util.Map;

import com.google.common.collect.Maps;

import fons.model.ontology.Dimension;

public class DynamicDimensionDefinition {
	private final String definition;
	private Dimension parent;
	
	public DynamicDimensionDefinition(String definition) {
		this.definition = definition;
	}
	
	public void setParent (Dimension dimension) {
		this.parent = dimension;
	}
	
	public boolean hasParent() {
		return this.parent != null;
	}
	
	public Dimension getParent() {
		return this.parent;
	}
	

	public String use(Map<String, Variable> variables) {

		final Map<String, Dimension> namedDimensions = Maps.newHashMap();
		
		for (Variable variable: variables.values()) {
			namedDimensions.putAll(variable.getNamedDimensions());
		}
		
		StringBuilder buffer = new StringBuilder(definition);
		
		for (String key: namedDimensions.keySet()) {
			final String pattern = "%" + key + "%";
			while (buffer.indexOf(pattern) != -1) {
				buffer.replace(buffer.indexOf(pattern), 
						buffer.indexOf(pattern) + pattern.length(), 
						namedDimensions.get(key).getName());
			}
		}
		
		return buffer.toString();
	}

	@Override
	public String toString() {
		return "DynamicDimensionDefinition [definition=" + definition + "]";
	}

}
